package com.xhwl.logistics.strategy.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.bo.manipulate.CreateVehicleCarBO;
import com.xhwl.logistics.bo.manipulate.DeleteVehicleCarBO;
import com.xhwl.logistics.bo.manipulate.UpdateVehicleCarBO;
import com.xhwl.logistics.entity.VehicleCar;
import com.xhwl.logistics.entity.VehicleCard;
import com.xhwl.logistics.entity.VehicleRelationCarToCard;
import com.xhwl.logistics.enums.VehicleCardTypeEnum;
import com.xhwl.logistics.service.impl.VehicleCarServiceImpl;
import com.xhwl.logistics.service.impl.VehicleCardServiceImpl;
import com.xhwl.logistics.service.impl.VehicleRelationCarToCardServiceImpl;
import com.xhwl.logistics.service.impl.http.ChuangXiangHttpServiceImpl;
import com.xhwl.logistics.strategy.IVehicleParkingLotCarAuthHandler;
import com.xhwl.logistics.util.AboutDateUtil;
import com.xhwl.logistics.util.MathUtil;
import com.xhwl.logistics.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 调用创享服务来对月租车进行授权
 */
@Slf4j
//@Service
public class VehicleParkingLotChuangXiangCarAuthHandlerImpl implements IVehicleParkingLotCarAuthHandler {

    @Autowired
    private ChuangXiangHttpServiceImpl chuangXiangHttpService;

    @Autowired
    private VehicleCardServiceImpl vehicleCardService;

    @Autowired
    private VehicleCarServiceImpl vehicleCarService;

    @Autowired
    private VehicleRelationCarToCardServiceImpl vehicleRelationCarToCardService;

    private static final String carType = "小车";

    /**
     * 通过项目id和卡类型cardType查询车卡的条件
     */
    private Wrapper<VehicleCard> conditionForCardByProjectIdAndCardType(Integer projectId, Integer cardType){
        return new LambdaQueryWrapper<VehicleCard>()
                .eq(VehicleCard::getProjectId, projectId)
                .eq(VehicleCard::getCardType, cardType);
    }

    /**
     * 通过项目id和车id查询车与车卡的关系的条件
     */
    private Wrapper<VehicleRelationCarToCard> conditionForRelationByProjectIdAndCarId(Integer projectId, Integer carId){
        return new LambdaQueryWrapper<VehicleRelationCarToCard>()
                .eq(VehicleRelationCarToCard::getProjectId, projectId)
                .eq(VehicleRelationCarToCard::getCarId, carId);
    }

    @Override
    public void addCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, CreateVehicleCarBO createVehicleCarBO) {
//        CreateVehicleCarBO createVehicleCarBO = JSONObject.parseObject(carDataStr, CreateVehicleCarBO.class);

        if(!MathUtil.equalsInterger(createVehicleCarBO.getCardType(), VehicleCardTypeEnum.MONTH.getId(), true, "卡类型不能为空")){
            throw new BusinessException("该项目暂时不能为非月卡车进行授权");
        }

        List<VehicleCard> vehicleCardList = vehicleCardService.list(conditionForCardByProjectIdAndCardType(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                createVehicleCarBO.getCardType()));
        if(vehicleCardList.isEmpty()){
            throw new BusinessException("未找到指定卡类型的信息，请先同步卡类型信息");
        }
        VehicleCard vehicleCard = vehicleCardList.get(0);

        chuangXiangHttpService.addOrUpdateMonthCar(vehicleIntegratedConfigBO, createVehicleCarBO.getOwnerName(), createVehicleCarBO.getOwnerPhone(),
                createVehicleCarBO.getPlateNumber(), vehicleCard.getThirdRuleId(), getChuangXiangCarModelId(vehicleIntegratedConfigBO),
                AboutDateUtil.dateToString(createVehicleCarBO.getValidStartTime()), AboutDateUtil.dateToString(createVehicleCarBO.getValidEndTime()));
    }

    @Override
    public void updateCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, String carDataStr) {
        UpdateVehicleCarBO updateVehicleCarBO = JSONObject.parseObject(carDataStr, UpdateVehicleCarBO.class);

        VehicleCar vehicleCar = vehicleCarService.getById(updateVehicleCarBO.getId());
        List<VehicleRelationCarToCard> vehicleRelationCarToCardList = vehicleRelationCarToCardService.list(conditionForRelationByProjectIdAndCarId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleCar.getId()));
        if(vehicleRelationCarToCardList.isEmpty()){
            throw new BusinessException("该条车辆信息与车卡信息被删除了，故无法更新");
        }
        VehicleRelationCarToCard vehicleRelationCarToCard = vehicleRelationCarToCardList.get(0);

        List<VehicleCard> vehicleCardList = vehicleCardService.list(conditionForCardByProjectIdAndCardType(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                VehicleCardTypeEnum.MONTH.getId()));
        if(vehicleCardList.isEmpty()){
            throw new BusinessException("未找到月卡类型的信息，请先同步卡类型信息");
        }
        VehicleCard vehicleCard = vehicleCardList.get(0);

        //如果车牌号变化了，需要先删除创享的车辆信息
        if(!StringUtils.equals(vehicleCar.getPlateNumber(), updateVehicleCarBO.getPlateNumber())){
            chuangXiangHttpService.deleteMonthCar(vehicleIntegratedConfigBO, vehicleCar.getPlateNumber());
        }

        chuangXiangHttpService.addOrUpdateMonthCar(vehicleIntegratedConfigBO, updateVehicleCarBO.getOwnerName(), updateVehicleCarBO.getOwnerPhone(),
                updateVehicleCarBO.getPlateNumber(), vehicleCard.getThirdRuleId(), getChuangXiangCarModelId(vehicleIntegratedConfigBO),
                AboutDateUtil.dateToString(vehicleRelationCarToCard.getValidStartTime()), AboutDateUtil.dateToString(vehicleRelationCarToCard.getValidEndTime()));
    }

    @Override
    public void deleteCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, String carDataStr) {
        DeleteVehicleCarBO deleteVehicleCarBO = JSONObject.parseObject(carDataStr, DeleteVehicleCarBO.class);

        VehicleCar vehicleCar = vehicleCarService.getById(deleteVehicleCarBO.getId());

        chuangXiangHttpService.deleteMonthCar(vehicleIntegratedConfigBO, vehicleCar.getPlateNumber());
    }

    /**
     * 获取创享指定车的车型id
     */
    private String getChuangXiangCarModelId(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        JSONArray carTypeInfo = chuangXiangHttpService.getCarTypeInfo(vehicleIntegratedConfigBO);
        List<JSONObject> carTypes = carTypeInfo.stream().map(o -> (JSONObject) o)
                .filter(s -> StringUtils.equals(s.getString("carmodelName"), carType))
                .collect(Collectors.toList());
        if(carTypes.isEmpty()){
            throw new BusinessException("创享的车型接口有变化，请联系开发人员");
        }
        return carTypes.get(0).getString("carmodelId");
    }

    /**
     * 月卡续期
     */
    @Override
    public void chargeMonthCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, JSONObject reqData) {
        Integer carId = ServletUtils.getValidateParamInt(reqData, "id", "车id为空");
        VehicleCar vehicleCar = vehicleCarService.getById(carId);
        if(vehicleCar == null){
            throw new BusinessException("通过车id无法找到车辆信息");
        }

        //根据项目id和车id查询车及车卡的联系
        List<VehicleRelationCarToCard> vehicleRelationCarToCards = vehicleRelationCarToCardService.list(conditionForRelationByProjectIdAndCarId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(), carId));
        if(vehicleRelationCarToCards.isEmpty()){
            throw new BusinessException("该条车辆信息与车卡信息被删除了，故无法更新");
        }
        VehicleRelationCarToCard vehicleRelationCarToCard = vehicleRelationCarToCards.get(0);

        chuangXiangHttpService.chargeMonthCar(vehicleIntegratedConfigBO, reqData, vehicleCar.getPlateNumber(), vehicleRelationCarToCard.getValidEndTime());
    }
}
